<?php

namespace App\Http\Controllers\Assets;

use App\Http\Controllers\Controller;
use App\Models\Assets\AccountingModel;
use App\Models\Assets\ExpensesByDayModel;
use App\Models\Assets\ExpensesModel;
use App\Service\Assets\AssetsService;
use Carbon\Carbon;
use Illuminate\Http\Request;

/**
 * 支出
 */
class ExpensesController extends Controller
{
    public function expensesAdd (Request $request)
    {
        $amount            = $request->post('amount', 0);
        $expenses          = new ExpensesModel();
        $expenses->user_id = $request->user_id;
        $expenses->amount  = $amount * 100;
        $expenses->save();

        return $this->success();
    }

    public function expensesTrend (Request $request)
    {
        $days   = $request->get('days', 10);
        $trends = ExpensesByDayModel::query()
                                    ->orderByDesc('id')
                                    ->where('user_id', $request->user_id)
                                    ->limit($days)
                                    ->get();

        // 汇总今天的总额
        $todayAmount = AssetsService::expenses($request->user_id);

        // 将分转换为元，并保留两位小数
        $formattedTrends = $trends->map(function ($item) {
            $item->amount = number_format($item->amount / 100, 2, '.', '');
            return $item;
        });

        return $this->success([
            'today'   => number_format($todayAmount / 100, 2, '.', ''),
            'list'    => $formattedTrends->toArray(),
            'total'   => $formattedTrends->sum('amount'),
            'average' => number_format($formattedTrends->avg('amount'), 2, '.', ''),
        ]);
    }


    /**
     * 账单列表
     */
    public function accounting (Request $request)
    {
        $timeRange = $request->get('timeRange');
        $time      = $request->get('time');

        if ($timeRange == 'day') {
            $startTime = Carbon::parse($time)
                               ->startOfDay()->timestamp;
            $endTime   = Carbon::parse($time)
                               ->endOfDay()->timestamp;
        } else {
            $startTime = Carbon::parse($time)
                               ->startOfMonth()->timestamp;
            $endTime   = Carbon::parse($time)
                               ->endOfMonth()->timestamp;
        }

        // 获得列表
        $list = AccountingModel::query()
                               ->where('user_id', $request->user()->id)
                               ->whereBetween('created_at', [
                                   $startTime,
                                   $endTime
                               ])
                               ->orderByDesc('created_at')
                               ->get();

        // 统计支出总额（type=0），需要扣除退款金额
        $expensesData  = AccountingModel::query()
                                        ->selectRaw('SUM(amount) as total_amount, SUM(refund) as total_refund')
                                        ->where('user_id', $request->user()->id)
                                        ->where('type', AccountingModel::TYPE_EXPENSE)
                                        ->whereBetween('created_at', [
                                            $startTime,
                                            $endTime
                                        ])
                                        ->first();
        $totalExpenses = ($expensesData->total_amount ?? 0) - ($expensesData->total_refund ?? 0);

        // 统计收入总额（type=1），需要扣除退款金额
        $revenuesData  = AccountingModel::query()
                                        ->selectRaw('SUM(amount) as total_amount, SUM(refund) as total_refund')
                                        ->where('user_id', $request->user()->id)
                                        ->where('type', AccountingModel::TYPE_INCOME)
                                        ->whereBetween('created_at', [
                                            $startTime,
                                            $endTime
                                        ])
                                        ->first();
        $totalRevenues = ($revenuesData->total_amount ?? 0) - ($revenuesData->total_refund ?? 0);

        return $this->success([
            'list'           => $list->toArray(),
            'total_expenses' => number_format($totalExpenses / 100, 2, '.', ''),
            'total_revenues' => number_format($totalRevenues / 100, 2, '.', ''),
            'balance'        => number_format(($totalRevenues - $totalExpenses) / 100, 2, '.', ''),
        ]);
    }

    /**
     * 添加账单
     */
    /**
     * 添加账单
     */
    public function addAccounting (Request $request)
    {
        $type        = $request->post('type', 0);
        $amount      = $request->post('amount', 0);
        $description = $request->post('description', '');
        $icon        = $request->post('icon', '');
        $accountId   = $request->post('account_id', 0);
        $createdTime = $request->post('created_at', Carbon::now()
                                                          ->toDateTimeString());

        // 参数验证
        if ($amount <= 0) {
            return $this->error('金额必须大于0');
        }

        if (!in_array($type, [
            AccountingModel::TYPE_EXPENSE,
            AccountingModel::TYPE_INCOME
        ])) {
            return $this->error('类型参数错误');
        }

        // 创建账单记录
        $accounting = AccountingModel::create([
            'user_id'     => $request->user()->id,
            'type'        => $type,
            'amount'      => $amount,
            'refund'      => 0,
            'description' => $description,
            'account_id'  => $accountId,
            'icon'        => $icon,
            'created_at'  => Carbon::create($createdTime)->timestamp,
            'updated_at'  => time(),
        ]);

        return $this->success([
            'id' => $accounting->id,
        ], '添加成功');
    }

    public function refund (Request $request, $id)
    {
        $refundAmount = $request->post('refund', 0);

        // 修改
        $accountingModel = AccountingModel::query()
                                          ->where('id', $id)
                                          ->first();

        $accountingModel->refund = $refundAmount + $accountingModel->refund;

        $accountingModel->save();

        return $this->success([], '添加成功');
    }

    public function delete (Request $request, $id)
    {
        AccountingModel::query()
                       ->where('id', $id)
                       ->delete();
        return $this->success([], '删除成功');
    }
}
